import AuthenticationContext from 'adal-angular/lib/adal.js'
// import { setToken } from '@/utils/auth'

const config = {
  tenant: 'qdlsai.org',
  clientId: '77703e2b-f001-49d3-b5cc-ebf775f7a33e',
  redirectUri: 'http://localhost:9528',
  cacheLocation: 'localStorage'
}
if (process.env.NODE_ENV === 'production') {
  config.tenant = ''
}
export default {
  authenticationContext: null,
  /**
   * @return {Promise}
   */
  initialize() {
    this.authenticationContext = new AuthenticationContext(config)

    return new Promise((resolve, _reject) => {
      if (this.authenticationContext.isCallback(window.location.hash) || window.self !== window.top) {
        // redirect to the location specified in the url params.
        this.authenticationContext.handleWindowCallback()
      } else {
        // try pull the user out of local storage
        const user = this.authenticationContext.getCachedUser()

        if (user) {
          this.acquireToken().then(token => {
            // Set token(可以存储，暂不使用)
            // setToken(token)
          })
          resolve()
        } else {
          // no user at all - go sign in.
          this.signIn()
        }
      }
    })
  },
  /**
   * @return {Promise.<String>} A promise that resolves to an ADAL token for resource access
   */
  acquireToken() {
    return new Promise((resolve, reject) => {
      this.authenticationContext.acquireToken('https://qdlsai.org/HSElearning.WebAPI', (error, token) => {
        if (error || !token) {
          return reject(error)
        } else {
          return resolve(token)
        }
      })
    })
  },
  /**
   * Issue an interactive authentication request for the current user and the api resource.
   */
  acquireTokenRedirect() {
    this.authenticationContext.acquireTokenRedirect('https://qdlsai.org/HSElearning.WebAPI')
  },
  /**
   * @return {Boolean} Indicates if there is a valid, non-expired access token present in localStorage.
   */
  isAuthenticated() {
    // getCachedToken will only return a valid, non-expired token.
    if (this.authenticationContext.getCachedToken(config.clientId)) { return true }
    return false
  },
  /**
   * @return An ADAL user profile object.
   */
  getUserProfile() {
    return this.authenticationContext.getCachedUser().profile
  },
  signIn() {
    this.authenticationContext.login()
  },
  signOut() {
    this.authenticationContext.logOut()
  }
}
